import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'package:like_button/like_button.dart';
import 'dart:io';

import 'index.dart';

class MePage extends StatefulWidget {
  const MePage({Key? key}) : super(key: key);

  @override
  State<MePage> createState() => _MePageState();
}

class _MePageState extends State<MePage> with RouteAware {
  final MeController controller = Get.put(MeController());

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 订阅路由观察器
    final ModalRoute<dynamic>? route = ModalRoute.of(context);
    if (route != null) {
      routeObserver.subscribe(this, route);
      print('MePage 已订阅路由观察器');
    }
  }

  @override
  void didPopNext() {
    // 当页面重新可见时，刷新数据
    print('MePage 重新获得焦点');
    controller.initData();
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    super.dispose();
  }

  // 构建个人数据区域
  Widget _buildProfileHeader() {
    return Obx(() {
      final user = controller.pageUser.value;
      final isOwnProfile = controller.isOwnProfile.value;

      // 如果用户未登录且是从导航栏进入，显示登录按钮
      if (user == null && controller.isFromNavBar.value) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'Please login to view your profile',
                style: TextStyle(fontSize: 18.sp, color: Colors.white),
              ),
              SizedBox(height: 20.h),
              ElevatedButton(
                onPressed: () => controller.goToLogin(),
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF4580DD),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  padding: EdgeInsets.symmetric(
                    horizontal: 30.w,
                    vertical: 12.h,
                  ),
                ),
                child: Text(
                  'Login',
                  style: TextStyle(fontSize: 16.sp, color: Colors.white),
                ),
              ),
            ],
          ),
        );
      }

      // 显示用户个人资料
      return Container(
        color: Colors.transparent,
        padding: EdgeInsets.only(
          left: 20.w,
          right: 20.w,
          top: 15.h,
          bottom: 20.h,
        ),
        child: Column(
          children: [
            // 用户头像、用户名和按钮区域
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // 用户头像
                Container(
                  width: 70.w,
                  height: 70.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(width: 3, color: Colors.white),
                  ),
                  child: ClipOval(
                    child:
                        user?.avatar != null && user!.avatar!.isNotEmpty
                            ? (user.avatar!.startsWith('assets/')
                                ? Image.asset(user.avatar!, fit: BoxFit.cover)
                                : Image.file(
                                  File(user.avatar!),
                                  fit: BoxFit.cover,
                                  errorBuilder: (context, error, stackTrace) {
                                    return Image.asset(
                                      Images.avatar1,
                                      fit: BoxFit.cover,
                                    );
                                  },
                                ))
                            : Image.asset(Images.avatar1, fit: BoxFit.cover),
                  ),
                ),
                SizedBox(width: 15.w),

                // 用户名和按钮
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        user?.nickname ?? user?.username ?? 'User',
                        style: TextStyle(
                          fontSize: 22.sp,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                          fontFamily: "ProtestStrike",
                        ),
                      ),
                    ],
                  ),
                ),

                // 个人资料按钮或聊天按钮
                if (isOwnProfile)
                  Container(
                    height: 36.h,
                    padding: EdgeInsets.symmetric(horizontal: 8.w),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(18.r),
                    ),
                    child: TextButton(
                      onPressed: () => controller.goToPersonalData(),
                      style: TextButton.styleFrom(
                        padding: EdgeInsets.zero,
                        minimumSize: Size.zero,
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            IconFontIcons.iconEdit,
                            color: const Color(0xFF0F3876),
                            size: 18.sp,
                          ),
                          SizedBox(width: 4.w),
                          Text(
                            'Personal Data',
                            style: TextStyle(
                              color: const Color(0xFF0F3876),
                              fontSize: 12.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ],
                      ),
                    ),
                  )
                else
                  OutlinedButton(
                    onPressed: () => controller.goToChat(),
                    style: OutlinedButton.styleFrom(
                      backgroundColor: Colors.white,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20.r),
                      ),
                      padding: EdgeInsets.symmetric(
                        horizontal: 12.w,
                        vertical: 6.h,
                      ),
                    ),
                    child: Text(
                      'Chat',
                      style: TextStyle(
                        color: const Color(0xFF0F3876),
                        fontSize: 14.sp,
                      ),
                    ),
                  ),

                // 关注按钮 (仅在查看他人主页时显示)
                if (!isOwnProfile) SizedBox(width: 10.w),
                if (!isOwnProfile)
                  Obx(
                    () => LikeButton(
                      size: 30.sp,
                      isLiked: controller.isFollowing.value,
                      onTap: (isFollowed) async {
                        await controller.toggleFollow();
                        return controller.isFollowing.value;
                      },
                      circleColor: CircleColor(
                        start: Color(0xFF3B5998),
                        end: Color(0xFF8B9DC3),
                      ),
                      bubblesColor: BubblesColor(
                        dotPrimaryColor: Color(0xFF3B5998),
                        dotSecondaryColor: Color(0xFF8B9DC3),
                        dotThirdColor: Color(0xFF4267B2),
                        dotLastColor: Color(0xFF5B7BD5),
                      ),
                      likeBuilder: (bool isFollowed) {
                        return Icon(
                          isFollowed ? Icons.person_remove : Icons.person_add,
                          color: Colors.white,
                          size: 24.sp,
                        );
                      },
                    ),
                  ),
              ],
            ),

            SizedBox(height: 20.h),

            // 统计数据区域
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildStatItem(
                  controller.followingCount.value.toString(),
                  'Followers',
                  onTap: () => controller.goToFollowers(),
                ),
                _buildStatItem(
                  controller.followersCount.value.toString(),
                  'Fans',
                  onTap: () => controller.goToFans(),
                ),
                _buildStatItem(
                  controller.groupsCount.value.toString(),
                  'Groups',
                  onTap: () => controller.goToGroups(),
                ),
                _buildStatItem(
                  controller.chatCount.value.toString(),
                  'Chat',
                  onTap: () => controller.goToChats(),
                ),
              ],
            ),

            SizedBox(height: 24.h),

            Divider(color: Colors.white.withOpacity(0.5), height: 1.h),
          ],
        ),
      );
    });
  }

  // 构建统计数据项
  Widget _buildStatItem(String count, String label, {VoidCallback? onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.baseline,
        textBaseline: TextBaseline.alphabetic,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            count,
            style: TextStyle(
              fontSize: 24.sp,
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
          ),
          SizedBox(width: 2.w),
          Text(
            label,
            style: TextStyle(
              fontSize: 12.sp,
              color: Colors.white70,
              fontWeight: FontWeight.w500,
              fontFamily: "Inter",
            ),
          ),
        ],
      ),
    );
  }

  // 构建Tab内容
  Widget _buildTabContent() {
    return Obx(() {
      if (controller.pageUser.value == null) {
        return SizedBox.shrink();
      }

      return Column(
        children: [
          AnimatedBuilder(
            animation: controller.tabController.animation!,
            builder: (context, child) {
              return Container(
                height: 45.h,
                width: double.infinity,
                decoration: BoxDecoration(color: Colors.transparent),
                child: Column(
                  children: [
                    // Tab标签区域
                    Expanded(
                      child: Padding(
                        padding: EdgeInsets.only(left: 20.w),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            _buildTabItem(0, 'Like'),
                            SizedBox(width: 24.w),
                            _buildTabItem(1, 'Recommend'),
                            SizedBox(width: 24.w),
                            _buildTabItem(2, 'Release'),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              );
            },
          ),

          // Tab内容区域
          Expanded(
            child: TabBarView(
              controller: controller.tabController,
              physics: const ClampingScrollPhysics(),
              children: [
                // Like Tab: 收藏的内容（视频、陶瓷作品）
                _buildLikeTabContent(),

                // Recommend Tab: 点赞的内容（视频、陶瓷作品）
                _buildRecommendTabContent(),

                // Release Tab: 发布的内容（陶瓷作品）
                _buildReleaseTabContent(),
              ],
            ),
          ),
        ],
      );
    });
  }

  // 构建单个Tab项
  Widget _buildTabItem(int index, String title) {
    // 获取当前动画值，用于平滑过渡
    double animationValue =
        controller.tabController.animation?.value ??
        controller.tabController.index.toDouble();

    // 计算选中状态的程度 (0.0 到 1.0)
    double selectedPercent =
        1.0 - (animationValue - index).abs().clamp(0.0, 1.0);

    // 混合颜色
    final Color textColor =
        Color.lerp(
          const Color(0xFFADC5E8), // 未选中颜色
          Colors.white, // 选中颜色
          selectedPercent,
        )!;

    // 混合字重
    final FontWeight fontWeight =
        selectedPercent > 0.5 ? FontWeight.w700 : FontWeight.w500;

    return GestureDetector(
      onTap: () {
        controller.tabController.animateTo(index);
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 标签文本
          Text(
            title,
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: fontWeight,
              color: textColor,
              fontFamily: "ProtestStrike",
            ),
          ),
          SizedBox(height: 6.h),
          // 指示器
          Container(
            height: 4.h,
            width: 10.w,
            decoration: BoxDecoration(
              color: Color.lerp(
                Colors.transparent,
                Colors.white,
                selectedPercent,
              ),
              borderRadius: BorderRadius.circular(1.5.r),
            ),
          ),
        ],
      ),
    );
  }

  // 构建收藏Tab内容
  Widget _buildLikeTabContent() {
    return Obx(() {
      final ceramics = controller.favoritedCeramics;
      final videos = controller.favoritedVideos;

      // 合计内容数
      final totalItems = ceramics.length + videos.length;

      if (totalItems == 0) {
        return Center(
          child: Column(
            children: [
              Image.asset(
                Images.empty,
                width: 60.w,
                height: 76.h,
                fit: BoxFit.cover,
              ),
              SizedBox(height: 10.h),
              Text(
                'No favorite items',
                style: TextStyle(color: Colors.white70, fontSize: 16.sp),
              ),
            ],
          ),
        );
      }

      return ListView.builder(
        padding: EdgeInsets.symmetric(vertical: 10.h),
        itemCount: totalItems,
        itemBuilder: (context, index) {
          // 判断内容类型
          if (index < videos.length) {
            // 视频
            final video = videos[index];
            return _buildVideoCard(
              video,
              'favorite',
              key: ValueKey('video_fav_${video.id}'),
            );
          } else {
            // 陶瓷作品
            final ceramic = ceramics[index - videos.length];
            return _buildCeramicCard(
              ceramic,
              'favorite',
              key: ValueKey('ceramic_fav_${ceramic.id}'),
            );
          }
        },
      );
    });
  }

  // 构建推荐Tab内容
  Widget _buildRecommendTabContent() {
    return Obx(() {
      final ceramics = controller.likedCeramics;
      final videos = controller.likedVideos;

      // 合计内容数（不包含官方内容）
      final totalItems = ceramics.length + videos.length;

      if (totalItems == 0) {
        return Center(
          child: Column(
            children: [
              Image.asset(
                Images.empty,
                width: 60.w,
                height: 76.h,
                fit: BoxFit.cover,
              ),
              SizedBox(height: 10.h),
              Text(
                'No liked items',
                style: TextStyle(color: Colors.white70, fontSize: 16.sp),
              ),
            ],
          ),
        );
      }

      return ListView.builder(
        padding: EdgeInsets.symmetric(vertical: 10.h),
        itemCount: totalItems,
        itemBuilder: (context, index) {
          // 判断内容类型
          if (index < videos.length) {
            // 视频
            final video = videos[index];
            return _buildVideoCard(
              video,
              'like',
              key: ValueKey('video_like_${video.id}'),
            );
          } else {
            // 陶瓷作品
            final ceramic = ceramics[index - videos.length];
            return _buildCeramicCard(
              ceramic,
              'like',
              key: ValueKey('ceramic_like_${ceramic.id}'),
            );
          }
        },
      );
    });
  }

  // 构建发布Tab内容
  Widget _buildReleaseTabContent() {
    return Obx(() {
      final ceramics = controller.publishedCeramics;

      if (ceramics.isEmpty) {
        return Center(
          child: Column(
            children: [
              Image.asset(
                Images.empty,
                width: 60.w,
                height: 76.h,
                fit: BoxFit.cover,
              ),
              SizedBox(height: 10.h),
              Text(
                'No published items',
                style: TextStyle(color: Colors.white70, fontSize: 16.sp),
              ),
            ],
          ),
        );
      }

      return ListView.builder(
        padding: EdgeInsets.symmetric(vertical: 10.h),
        itemCount: ceramics.length,
        itemBuilder: (context, index) {
          final ceramic = ceramics[index];
          return _buildCeramicCard(
            ceramic,
            'publish',
            key: ValueKey('ceramic_pub_${ceramic.id}'),
          );
        },
      );
    });
  }

  // 构建视频卡片
  Widget _buildVideoCard(RecommendedVideo video, String action, {Key? key}) {
    return GestureDetector(
      key: key,
      onTap: () {
        // 根据来源跳转到视频详情页
        if (action == 'favorite') {
          // 从收藏列表进入
          final index = controller.favoritedVideos.indexOf(video);
          if (index != -1) {
            controller.goToFavoriteVideoDetail(index);
          }
        } else if (action == 'like') {
          // 从点赞列表进入
          final index = controller.likedVideos.indexOf(video);
          if (index != -1) {
            controller.goToLikedVideoDetail(index);
          }
        }
      },
      child: Container(
        width: double.infinity,
        margin: EdgeInsets.symmetric(horizontal: 15.w, vertical: 8.h),
        padding: EdgeInsets.all(10.r),
        decoration: ShapeDecoration(
          color: const Color(0xFF305CA9),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        child: Column(
          children: [
            // 视频封面和播放图标
            Stack(
              children: [
                Container(
                  height: 254.h,
                  decoration: ShapeDecoration(
                    image: DecorationImage(
                      image: _getImageProvider(video.thumbnailUrl),
                      fit: BoxFit.cover,
                    ),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                  ),
                ),
                // 播放图标
                Positioned.fill(
                  child: Center(
                    child: Icon(
                      IconFontIcons.iconPlay,
                      color: Colors.white,
                      size: 48.sp,
                    ),
                  ),
                ),
              ],
            ),
            SizedBox(height: 12.h),
            Row(
              children: [
                // 浏览过的用户头像
                _buildViewedUsers(video.id!, BrowseType.video),
                Spacer(),
                // 收藏按钮
                LikeButton(
                  size: 24.sp,
                  isLiked:
                      video.id != null
                          ? controller.isVideoFavorited(video.id!)
                          : false,
                  animationDuration: Duration(milliseconds: 800),
                  circleColor: CircleColor(
                    start: Color(0xFFFF5722),
                    end: Color(0xFFFFC107),
                  ),
                  bubblesColor: BubblesColor(
                    dotPrimaryColor: Color(0xFFFF5722),
                    dotSecondaryColor: Color(0xFFFFC107),
                    dotThirdColor: Color(0xFFFF9800),
                    dotLastColor: Color(0xFFF44336),
                  ),
                  likeBuilder: (bool isLiked) {
                    return Icon(
                      isLiked
                          ? IconFontIcons.iconLikeFill
                          : IconFontIcons.iconLike,
                      color: isLiked ? Colors.red : Colors.white,
                      size: 24.sp,
                    );
                  },
                  onTap: (isLiked) async {
                    return await controller.toggleVideoFavorite(video);
                  },
                ),
                SizedBox(width: 27.w),
                // 点赞按钮
                LikeButton(
                  size: 24.sp,
                  isLiked:
                      video.id != null
                          ? controller.isVideoLiked(video.id!)
                          : false,
                  animationDuration: Duration(milliseconds: 800),
                  circleColor: CircleColor(
                    start: Color(0xFF00DDFF),
                    end: Color(0xFF0099CC),
                  ),
                  bubblesColor: BubblesColor(
                    dotPrimaryColor: Color(0xFF33B5E5),
                    dotSecondaryColor: Color(0xFF0099CC),
                    dotThirdColor: Color(0xFF00DDFF),
                    dotLastColor: Color(0xFF00AACC),
                  ),
                  likeBuilder: (bool isLiked) {
                    return Icon(
                      isLiked
                          ? IconFontIcons.iconGoodFill
                          : IconFontIcons.iconGood,
                      color: isLiked ? Colors.red : Colors.white,
                      size: 24.sp,
                    );
                  },
                  onTap: (isLiked) async {
                    return await controller.toggleVideoLike(video);
                  },
                ),
                SizedBox(width: 22.w),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 构建陶瓷作品卡片
  Widget _buildCeramicCard(Ceramic ceramic, String action, {Key? key}) {
    return GestureDetector(
      key: key,
      onTap: () {
        // 跳转到陶瓷详情页
        Get.toNamed(Routes.detail, arguments: {'ceramic': ceramic});
      },
      child: Container(
        width: double.infinity,
        margin: EdgeInsets.symmetric(horizontal: 15.w, vertical: 8.h),
        padding: EdgeInsets.all(10.r),
        decoration: ShapeDecoration(
          color: const Color(0xFF305CA9),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        child: Column(
          children: [
            // 陶瓷图片（无播放图标）
            Container(
              height: 254.h,
              decoration: ShapeDecoration(
                image: DecorationImage(
                  image: _getImageProvider(ceramic.imageUrl),
                  fit: BoxFit.cover,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12.r),
                ),
              ),
            ),
            SizedBox(height: 12.h),
            Row(
              children: [
                // 浏览过的用户头像
                _buildViewedUsers(ceramic.id!, BrowseType.ceramic),
                Spacer(),
                // 收藏按钮
                LikeButton(
                  size: 24.sp,
                  isLiked:
                      ceramic.id != null
                          ? controller.isCeramicFavorited(ceramic.id!)
                          : false,
                  animationDuration: Duration(milliseconds: 800),
                  circleColor: CircleColor(
                    start: Color(0xFFFF5722),
                    end: Color(0xFFFFC107),
                  ),
                  bubblesColor: BubblesColor(
                    dotPrimaryColor: Color(0xFFFF5722),
                    dotSecondaryColor: Color(0xFFFFC107),
                    dotThirdColor: Color(0xFFFF9800),
                    dotLastColor: Color(0xFFF44336),
                  ),
                  likeBuilder: (bool isLiked) {
                    return Icon(
                      isLiked
                          ? IconFontIcons.iconLikeFill
                          : IconFontIcons.iconLike,
                      color: isLiked ? Colors.red : Colors.white,
                      size: 24.sp,
                    );
                  },
                  onTap: (isLiked) async {
                    return await controller.toggleCeramicFavorite(ceramic);
                  },
                ),
                SizedBox(width: 27.w),
                // 点赞按钮
                LikeButton(
                  size: 24.sp,
                  isLiked:
                      ceramic.id != null
                          ? controller.isCeramicLiked(ceramic.id!)
                          : false,
                  animationDuration: Duration(milliseconds: 800),
                  circleColor: CircleColor(
                    start: Color(0xFF00DDFF),
                    end: Color(0xFF0099CC),
                  ),
                  bubblesColor: BubblesColor(
                    dotPrimaryColor: Color(0xFF33B5E5),
                    dotSecondaryColor: Color(0xFF0099CC),
                    dotThirdColor: Color(0xFF00DDFF),
                    dotLastColor: Color(0xFF00AACC),
                  ),
                  likeBuilder: (bool isLiked) {
                    return Icon(
                      isLiked
                          ? IconFontIcons.iconGoodFill
                          : IconFontIcons.iconGood,
                      color: isLiked ? Colors.red : Colors.white,
                      size: 24.sp,
                    );
                  },
                  onTap: (isLiked) async {
                    return await controller.toggleCeramicLike(ceramic);
                  },
                ),
                SizedBox(width: 22.w),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 构建浏览用户列表
  Widget _buildViewedUsers(int contentId, BrowseType type) {
    // 加载浏览用户数据
    controller.loadContentViewedUsers(contentId, type);

    return Obx(() {
      final isLoading = controller.isContentUsersLoading(contentId, type);
      final List<User> viewedUsers = controller.getContentViewedUsers(
        contentId,
        type,
      );

      if (isLoading) {
        return SizedBox(
          height: 44.w,
          child: Center(
            child: SizedBox(
              width: 20.w,
              height: 20.w,
              child: CircularProgressIndicator(
                strokeWidth: 2.0,
                color: Colors.white,
              ),
            ),
          ),
        );
      }

      return Row(
        children: [
          // 浏览用户头像
          if (viewedUsers.isNotEmpty) ...[
            SizedBox(
              height: 44.w,
              width: viewedUsers.length > 1 ? 30.w * viewedUsers.length : 44.w,
              child: Stack(
                children: List.generate(
                  viewedUsers.length > 4 ? 4 : viewedUsers.length,
                  (index) => Positioned(
                    left: index * 20.w,
                    child: Container(
                      height: 44.w,
                      width: 44.w,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(color: Colors.white, width: 2),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            blurRadius: 4,
                            spreadRadius: 1,
                          ),
                        ],
                      ),
                      child: ClipOval(
                        child:
                            viewedUsers[index].avatar != null
                                ? Image.asset(
                                  viewedUsers[index].avatar!,
                                  fit: BoxFit.cover,
                                )
                                : Container(
                                  color: Colors.grey[300],
                                  child: Icon(
                                    Icons.person,
                                    size: 25.sp,
                                    color: Colors.grey[600],
                                  ),
                                ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
            Text(
              'Already viewed',
              style: TextStyle(
                color: Colors.white70,
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
              ),
            ),
          ] else ...[
            // 没有浏览用户时显示
            Container(
              height: 44.w,
              width: 44.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Colors.white, width: 2),
              ),
              child: Center(
                child: Icon(Icons.add, size: 20.sp, color: Colors.white),
              ),
            ),
            SizedBox(width: 10.w),
            Text(
              'No one viewed',
              style: TextStyle(
                color: Colors.white70,
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
              ),
            ),
          ],
        ],
      );
    });
  }

  // 获取图片提供器（处理不同类型的图片路径）
  ImageProvider _getImageProvider(String? imageUrl) {
    if (imageUrl == null || imageUrl.isEmpty) {
      return AssetImage(Images.ceramic1);
    }

    // 处理本地文件路径（以/开头）
    if (imageUrl.startsWith('/')) {
      try {
        final file = File(imageUrl);
        if (file.existsSync()) {
          return FileImage(file);
        }
      } catch (e) {
        debugPrint('加载文件图片失败: $e');
      }
      return AssetImage(Images.ceramic1);
    }

    // 处理file:///开头的路径
    if (imageUrl.startsWith('file:///')) {
      String cleanPath = imageUrl.replaceFirst('file:///', '');
      return AssetImage(cleanPath);
    }

    // 处理http开头的网络图片
    if (imageUrl.startsWith('http')) {
      return NetworkImage(imageUrl);
    }

    // 默认作为asset加载
    return AssetImage(imageUrl);
  }

  // 构建加载指示器
  Widget _buildLoading() {
    return Center(
      child: CircularProgressIndicator(
        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
      ),
    );
  }

  // 主视图
  Widget _buildView() {
    return Obx(() {
      if (controller.isLoading.value) {
        return _buildLoading();
      }

      // 用户未登录且从导航栏进入时，只显示登录提示
      if (controller.pageUser.value == null && controller.isFromNavBar.value) {
        return _buildProfileHeader();
      }

      // 正常显示个人页面
      return Column(
        children: [_buildProfileHeader(), Expanded(child: _buildTabContent())],
      );
    });
  }

  // 构建AppBar
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: Colors.transparent,
      elevation: 0,
      centerTitle: true,
      title: Text(
        'personal',
        style: TextStyle(
          fontSize: 20.sp,
          color: Colors.white,
          fontWeight: FontWeight.w500,
        ),
      ),
      // 如果不是从导航栏进入，显示返回按钮
      leading:
          !controller.isFromNavBar.value
              ? IconButton(
                icon: Icon(Icons.arrow_back_ios, color: Colors.white),
                onPressed: () => Get.back(),
              )
              : null,
      // 右侧按钮
      actions: [
        Obx(() {
          // 如果用户未登录，不显示任何按钮
          if (controller.pageUser.value == null) {
            return SizedBox.shrink();
          }

          // 如果是个人主页，显示通知和设置按钮
          if (controller.isOwnProfile.value) {
            return Row(
              children: [
                IconButton(
                  icon: Icon(
                    IconFontIcons.iconNotify,
                    color: Colors.white,
                    size: 24.sp,
                  ),
                  onPressed: () => controller.goToNotifications(),
                ),
                IconButton(
                  icon: Icon(
                    IconFontIcons.iconSetup,
                    color: Colors.white,
                    size: 24.sp,
                  ),
                  onPressed: () => controller.goToSettings(),
                  padding: EdgeInsets.only(right: 10.w),
                ),
              ],
            );
          }
          // 如果是他人主页，显示举报按钮
          else {
            return IconButton(
              icon: Icon(IconFontIcons.iconReport, color: Colors.white),
              onPressed: () => controller.reportUser(),
              padding: EdgeInsets.only(right: 10.w),
            );
          }
        }),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return _MeViewGetX(controller: controller);
  }
}

class _MeViewGetX extends StatelessWidget {
  final MeController controller;

  const _MeViewGetX({Key? key, required this.controller}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      backgroundColor: Colors.transparent,
      appBar: _buildAppBar(),
      body: Stack(
        children: [
          // 添加背景图
          Positioned.fill(
            child: Image.asset(Images.startBg, fit: BoxFit.cover),
          ),
          // 原有内容
          SafeArea(child: _buildView()),
        ],
      ),
    );
  }

  // 构建个人数据区域
  Widget _buildProfileHeader() {
    return Obx(() {
      final user = controller.pageUser.value;
      final isOwnProfile = controller.isOwnProfile.value;

      // 如果用户未登录且是从导航栏进入，显示登录按钮
      if (user == null && controller.isFromNavBar.value) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'Please login to view your profile',
                style: TextStyle(fontSize: 18.sp, color: Colors.white),
              ),
              SizedBox(height: 20.h),
              ElevatedButton(
                onPressed: () => controller.goToLogin(),
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF4580DD),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  padding: EdgeInsets.symmetric(
                    horizontal: 30.w,
                    vertical: 12.h,
                  ),
                ),
                child: Text(
                  'Login',
                  style: TextStyle(fontSize: 16.sp, color: Colors.white),
                ),
              ),
            ],
          ),
        );
      }

      // 显示用户个人资料
      return Container(
        color: Colors.transparent,
        padding: EdgeInsets.only(
          left: 20.w,
          right: 20.w,
          top: 15.h,
          bottom: 20.h,
        ),
        child: Column(
          children: [
            // 用户头像、用户名和按钮区域
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // 用户头像
                Container(
                  width: 70.w,
                  height: 70.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(width: 2, color: Colors.white),
                  ),
                  child: ClipOval(
                    child:
                        user?.avatar != null && user!.avatar!.isNotEmpty
                            ? (user.avatar!.startsWith('assets/')
                                ? Image.asset(user.avatar!, fit: BoxFit.cover)
                                : Image.file(
                                  File(user.avatar!),
                                  fit: BoxFit.cover,
                                  errorBuilder: (context, error, stackTrace) {
                                    return Image.asset(
                                      Images.avatar1,
                                      fit: BoxFit.cover,
                                    );
                                  },
                                ))
                            : Image.asset(Images.avatar1, fit: BoxFit.cover),
                  ),
                ),
                SizedBox(width: 15.w),

                // 用户名和按钮
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        user?.nickname ?? user?.username ?? 'User',
                        style: TextStyle(
                          fontSize: 22.sp,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                          fontFamily: "ProtestStrike",
                        ),
                      ),
                    ],
                  ),
                ),

                // 个人资料按钮或聊天按钮
                if (isOwnProfile)
                  Container(
                    height: 36.h,
                    padding: EdgeInsets.symmetric(horizontal: 8.w),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(18.r),
                    ),
                    child: TextButton(
                      onPressed: () => controller.goToPersonalData(),
                      style: TextButton.styleFrom(
                        padding: EdgeInsets.zero,
                        minimumSize: Size.zero,
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            IconFontIcons.iconEdit,
                            color: const Color(0xFF0F3876),
                            size: 18.sp,
                          ),
                          SizedBox(width: 4.w),
                          Text(
                            'Personal Data',
                            style: TextStyle(
                              color: const Color(0xFF0F3876),
                              fontSize: 12.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ],
                      ),
                    ),
                  )
                else
                  OutlinedButton(
                    onPressed: () => controller.goToChat(),
                    style: OutlinedButton.styleFrom(
                      backgroundColor: Colors.white,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20.r),
                      ),
                      padding: EdgeInsets.symmetric(
                        horizontal: 12.w,
                        vertical: 6.h,
                      ),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          IconFontIcons.iconChat,
                          color: const Color(0xFF0F3876),
                          size: 18.sp,
                        ),
                        SizedBox(width: 4.w),
                        Text(
                          'Chat',
                          style: TextStyle(
                            color: const Color(0xFF0F3876),
                            fontSize: 12.sp,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ],
                    ),
                  ),

                // 关注按钮 (仅在查看他人主页时显示)
                // if (!isOwnProfile) SizedBox(width: 10.w),
                // if (!isOwnProfile)
                //   Obx(
                //     () => LikeButton(
                //       size: 30.sp,
                //       isLiked: controller.isFollowing.value,
                //       onTap: (isFollowed) async {
                //         await controller.toggleFollow();
                //         return controller.isFollowing.value;
                //       },
                //       circleColor: CircleColor(
                //         start: Color(0xFF3B5998),
                //         end: Color(0xFF8B9DC3),
                //       ),
                //       bubblesColor: BubblesColor(
                //         dotPrimaryColor: Color(0xFF3B5998),
                //         dotSecondaryColor: Color(0xFF8B9DC3),
                //         dotThirdColor: Color(0xFF4267B2),
                //         dotLastColor: Color(0xFF5B7BD5),
                //       ),
                //       likeBuilder: (bool isFollowed) {
                //         return Icon(
                //           isFollowed ? Icons.person_remove : Icons.person_add,
                //           color: Colors.white,
                //           size: 24.sp,
                //         );
                //       },
                //     ),
                //   ),
              ],
            ),

            SizedBox(height: 20.h),

            // 统计数据区域
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildStatItem(
                  controller.followingCount.value.toString(),
                  'Followers',
                  onTap: () => controller.goToFollowers(),
                ),
                _buildStatItem(
                  controller.followersCount.value.toString(),
                  'Fans',
                  onTap: () => controller.goToFans(),
                ),
                _buildStatItem(
                  controller.groupsCount.value.toString(),
                  'Groups',
                  onTap: () => controller.goToGroups(),
                ),
                _buildStatItem(
                  controller.chatCount.value.toString(),
                  'Chat',
                  onTap: () => controller.goToChats(),
                ),
              ],
            ),

            SizedBox(height: 24.h),

            Divider(color: Colors.white.withOpacity(0.5), height: 1.h),
          ],
        ),
      );
    });
  }

  // 构建统计数据项
  Widget _buildStatItem(String count, String label, {VoidCallback? onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.baseline,
        textBaseline: TextBaseline.alphabetic,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            count,
            style: TextStyle(
              fontSize: 24.sp,
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
          ),
          SizedBox(width: 2.w),
          Text(
            label,
            style: TextStyle(
              fontSize: 12.sp,
              color: Colors.white70,
              fontWeight: FontWeight.w500,
              fontFamily: "Inter",
            ),
          ),
        ],
      ),
    );
  }

  // 构建Tab内容
  Widget _buildTabContent() {
    return Obx(() {
      if (controller.pageUser.value == null) {
        return SizedBox.shrink();
      }

      return Column(
        children: [
          AnimatedBuilder(
            animation: controller.tabController.animation!,
            builder: (context, child) {
              return Container(
                height: 45.h,
                width: double.infinity,
                decoration: BoxDecoration(color: Colors.transparent),
                child: Column(
                  children: [
                    // Tab标签区域
                    Expanded(
                      child: Padding(
                        padding: EdgeInsets.only(left: 20.w),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            _buildTabItem(0, 'Like'),
                            SizedBox(width: 24.w),
                            _buildTabItem(1, 'Recommend'),
                            SizedBox(width: 24.w),
                            _buildTabItem(2, 'Release'),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              );
            },
          ),

          // Tab内容区域
          Expanded(
            child: TabBarView(
              controller: controller.tabController,
              physics: const ClampingScrollPhysics(),
              children: [
                // Like Tab: 收藏的内容（视频、陶瓷作品）
                _buildLikeTabContent(),

                // Recommend Tab: 点赞的内容（视频、陶瓷作品）
                _buildRecommendTabContent(),

                // Release Tab: 发布的内容（陶瓷作品）
                _buildReleaseTabContent(),
              ],
            ),
          ),
        ],
      );
    });
  }

  // 构建单个Tab项
  Widget _buildTabItem(int index, String title) {
    // 获取当前动画值，用于平滑过渡
    double animationValue =
        controller.tabController.animation?.value ??
        controller.tabController.index.toDouble();

    // 计算选中状态的程度 (0.0 到 1.0)
    double selectedPercent =
        1.0 - (animationValue - index).abs().clamp(0.0, 1.0);

    // 混合颜色
    final Color textColor =
        Color.lerp(
          const Color(0xFFADC5E8), // 未选中颜色
          Colors.white, // 选中颜色
          selectedPercent,
        )!;

    // 混合字重
    final FontWeight fontWeight =
        selectedPercent > 0.5 ? FontWeight.w700 : FontWeight.w500;

    return GestureDetector(
      onTap: () {
        controller.tabController.animateTo(index);
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 标签文本
          Text(
            title,
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: fontWeight,
              color: textColor,
              fontFamily: "ProtestStrike",
            ),
          ),
          SizedBox(height: 6.h),
          // 指示器
          Container(
            height: 4.h,
            width: 10.w,
            decoration: BoxDecoration(
              color: Color.lerp(
                Colors.transparent,
                Colors.white,
                selectedPercent,
              ),
              borderRadius: BorderRadius.circular(1.5.r),
            ),
          ),
        ],
      ),
    );
  }

  // 构建收藏Tab内容
  Widget _buildLikeTabContent() {
    return Obx(() {
      final ceramics = controller.favoritedCeramics;
      final videos = controller.favoritedVideos;

      // 合计内容数
      final totalItems = ceramics.length + videos.length;

      if (totalItems == 0) {
        return Center(
          child: Column(
            children: [
              SizedBox(height: 100.h),
              Image.asset(
                Images.empty,
                width: 60.w,
                height: 76.h,
                fit: BoxFit.cover,
              ),
              SizedBox(height: 10.h),
              Text(
                'No favorite items',
                style: TextStyle(color: Colors.white70, fontSize: 16.sp),
              ),
            ],
          ),
        );
      }

      return ListView.builder(
        padding: EdgeInsets.symmetric(vertical: 10.h),
        itemCount: totalItems,
        itemBuilder: (context, index) {
          // 判断内容类型
          if (index < videos.length) {
            // 视频
            final video = videos[index];
            return _buildVideoCard(
              video,
              'favorite',
              key: ValueKey('video_fav_${video.id}'),
            );
          } else {
            // 陶瓷作品
            final ceramic = ceramics[index - videos.length];
            return _buildCeramicCard(
              ceramic,
              'favorite',
              key: ValueKey('ceramic_fav_${ceramic.id}'),
            );
          }
        },
      );
    });
  }

  // 构建推荐Tab内容
  Widget _buildRecommendTabContent() {
    return Obx(() {
      final ceramics = controller.likedCeramics;
      final videos = controller.likedVideos;

      // 合计内容数（不包含官方内容）
      final totalItems = ceramics.length + videos.length;

      if (totalItems == 0) {
        return Center(
          child: Column(
            children: [
              SizedBox(height: 100.h),
              Image.asset(
                Images.empty,
                width: 60.w,
                height: 76.h,
                fit: BoxFit.cover,
              ),
              SizedBox(height: 10.h),
              Text(
                'No liked items',
                style: TextStyle(color: Colors.white70, fontSize: 16.sp),
              ),
            ],
          ),
        );
      }

      return ListView.builder(
        padding: EdgeInsets.symmetric(vertical: 10.h),
        itemCount: totalItems,
        itemBuilder: (context, index) {
          // 判断内容类型
          if (index < videos.length) {
            // 视频
            final video = videos[index];
            return _buildVideoCard(
              video,
              'like',
              key: ValueKey('video_like_${video.id}'),
            );
          } else {
            // 陶瓷作品
            final ceramic = ceramics[index - videos.length];
            return _buildCeramicCard(
              ceramic,
              'like',
              key: ValueKey('ceramic_like_${ceramic.id}'),
            );
          }
        },
      );
    });
  }

  // 构建发布Tab内容
  Widget _buildReleaseTabContent() {
    return Obx(() {
      final ceramics = controller.publishedCeramics;

      if (ceramics.isEmpty) {
        return Center(
          child: Column(
            children: [
              SizedBox(height: 100.h),
              Image.asset(
                Images.empty,
                width: 60.w,
                height: 76.h,
                fit: BoxFit.cover,
              ),
              SizedBox(height: 10.h),
              Text(
                'No published items',
                style: TextStyle(color: Colors.white70, fontSize: 16.sp),
              ),
            ],
          ),
        );
      }

      return ListView.builder(
        padding: EdgeInsets.symmetric(vertical: 10.h),
        itemCount: ceramics.length,
        itemBuilder: (context, index) {
          final ceramic = ceramics[index];
          return _buildCeramicCard(
            ceramic,
            'publish',
            key: ValueKey('ceramic_pub_${ceramic.id}'),
          );
        },
      );
    });
  }

  // 构建视频卡片
  Widget _buildVideoCard(RecommendedVideo video, String action, {Key? key}) {
    return GestureDetector(
      key: key,
      onTap: () {
        // 根据来源跳转到视频详情页
        if (action == 'favorite') {
          // 从收藏列表进入
          final index = controller.favoritedVideos.indexOf(video);
          if (index != -1) {
            controller.goToFavoriteVideoDetail(index);
          }
        } else if (action == 'like') {
          // 从点赞列表进入
          final index = controller.likedVideos.indexOf(video);
          if (index != -1) {
            controller.goToLikedVideoDetail(index);
          }
        }
      },
      child: Container(
        width: double.infinity,
        margin: EdgeInsets.symmetric(horizontal: 15.w, vertical: 8.h),
        padding: EdgeInsets.all(10.r),
        decoration: ShapeDecoration(
          color: const Color(0xFF305CA9),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        child: Column(
          children: [
            // 视频封面和播放图标
            Stack(
              children: [
                Container(
                  height: 254.h,
                  decoration: ShapeDecoration(
                    image: DecorationImage(
                      image: _getImageProvider(video.thumbnailUrl),
                      fit: BoxFit.cover,
                    ),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                  ),
                ),
                // 播放图标
                Positioned.fill(
                  child: Center(
                    child: Icon(
                      IconFontIcons.iconPlay,
                      color: Colors.white,
                      size: 48.sp,
                    ),
                  ),
                ),
              ],
            ),
            SizedBox(height: 12.h),
            Row(
              children: [
                // 浏览过的用户头像
                _buildViewedUsers(video.id!, BrowseType.video),
                Spacer(),
                // 收藏按钮
                LikeButton(
                  size: 24.sp,
                  isLiked:
                      video.id != null
                          ? controller.isVideoFavorited(video.id!)
                          : false,
                  animationDuration: Duration(milliseconds: 800),
                  circleColor: CircleColor(
                    start: Color(0xFFFF5722),
                    end: Color(0xFFFFC107),
                  ),
                  bubblesColor: BubblesColor(
                    dotPrimaryColor: Color(0xFFFF5722),
                    dotSecondaryColor: Color(0xFFFFC107),
                    dotThirdColor: Color(0xFFFF9800),
                    dotLastColor: Color(0xFFF44336),
                  ),
                  likeBuilder: (bool isLiked) {
                    return Icon(
                      isLiked
                          ? IconFontIcons.iconLikeFill
                          : IconFontIcons.iconLike,
                      color: isLiked ? Colors.red : Colors.white,
                      size: 24.sp,
                    );
                  },
                  onTap: (isLiked) async {
                    return await controller.toggleVideoFavorite(video);
                  },
                ),
                SizedBox(width: 27.w),
                // 点赞按钮
                LikeButton(
                  size: 24.sp,
                  isLiked:
                      video.id != null
                          ? controller.isVideoLiked(video.id!)
                          : false,
                  animationDuration: Duration(milliseconds: 800),
                  circleColor: CircleColor(
                    start: Color(0xFF00DDFF),
                    end: Color(0xFF0099CC),
                  ),
                  bubblesColor: BubblesColor(
                    dotPrimaryColor: Color(0xFF33B5E5),
                    dotSecondaryColor: Color(0xFF0099CC),
                    dotThirdColor: Color(0xFF00DDFF),
                    dotLastColor: Color(0xFF00AACC),
                  ),
                  likeBuilder: (bool isLiked) {
                    return Icon(
                      isLiked
                          ? IconFontIcons.iconGoodFill
                          : IconFontIcons.iconGood,
                      color: isLiked ? Colors.red : Colors.white,
                      size: 24.sp,
                    );
                  },
                  onTap: (isLiked) async {
                    return await controller.toggleVideoLike(video);
                  },
                ),
                SizedBox(width: 22.w),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 构建陶瓷作品卡片
  Widget _buildCeramicCard(Ceramic ceramic, String action, {Key? key}) {
    return GestureDetector(
      key: key,
      onTap: () {
        // 跳转到陶瓷详情页
        Get.toNamed(Routes.detail, arguments: {'ceramic': ceramic});
      },
      child: Container(
        width: double.infinity,
        margin: EdgeInsets.symmetric(horizontal: 15.w, vertical: 8.h),
        padding: EdgeInsets.all(10.r),
        decoration: ShapeDecoration(
          color: const Color(0xFF305CA9),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        child: Column(
          children: [
            // 陶瓷图片（无播放图标）
            Container(
              height: 254.h,
              decoration: ShapeDecoration(
                image: DecorationImage(
                  image: _getImageProvider(ceramic.imageUrl),
                  fit: BoxFit.cover,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12.r),
                ),
              ),
            ),
            SizedBox(height: 12.h),
            Row(
              children: [
                // 浏览过的用户头像
                _buildViewedUsers(ceramic.id!, BrowseType.ceramic),
                Spacer(),
                // 收藏按钮
                LikeButton(
                  size: 24.sp,
                  isLiked:
                      ceramic.id != null
                          ? controller.isCeramicFavorited(ceramic.id!)
                          : false,
                  animationDuration: Duration(milliseconds: 800),
                  circleColor: CircleColor(
                    start: Color(0xFFFF5722),
                    end: Color(0xFFFFC107),
                  ),
                  bubblesColor: BubblesColor(
                    dotPrimaryColor: Color(0xFFFF5722),
                    dotSecondaryColor: Color(0xFFFFC107),
                    dotThirdColor: Color(0xFFFF9800),
                    dotLastColor: Color(0xFFF44336),
                  ),
                  likeBuilder: (bool isLiked) {
                    return Icon(
                      isLiked
                          ? IconFontIcons.iconLikeFill
                          : IconFontIcons.iconLike,
                      color: isLiked ? Colors.red : Colors.white,
                      size: 24.sp,
                    );
                  },
                  onTap: (isLiked) async {
                    return await controller.toggleCeramicFavorite(ceramic);
                  },
                ),
                SizedBox(width: 27.w),
                // 点赞按钮
                LikeButton(
                  size: 24.sp,
                  isLiked:
                      ceramic.id != null
                          ? controller.isCeramicLiked(ceramic.id!)
                          : false,
                  animationDuration: Duration(milliseconds: 800),
                  circleColor: CircleColor(
                    start: Color(0xFF00DDFF),
                    end: Color(0xFF0099CC),
                  ),
                  bubblesColor: BubblesColor(
                    dotPrimaryColor: Color(0xFF33B5E5),
                    dotSecondaryColor: Color(0xFF0099CC),
                    dotThirdColor: Color(0xFF00DDFF),
                    dotLastColor: Color(0xFF00AACC),
                  ),
                  likeBuilder: (bool isLiked) {
                    return Icon(
                      isLiked
                          ? IconFontIcons.iconGoodFill
                          : IconFontIcons.iconGood,
                      color: isLiked ? Colors.red : Colors.white,
                      size: 24.sp,
                    );
                  },
                  onTap: (isLiked) async {
                    return await controller.toggleCeramicLike(ceramic);
                  },
                ),
                SizedBox(width: 22.w),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 构建浏览用户列表
  Widget _buildViewedUsers(int contentId, BrowseType type) {
    // 加载浏览用户数据
    controller.loadContentViewedUsers(contentId, type);

    return Obx(() {
      final isLoading = controller.isContentUsersLoading(contentId, type);
      final List<User> viewedUsers = controller.getContentViewedUsers(
        contentId,
        type,
      );

      if (isLoading) {
        return SizedBox(
          height: 44.w,
          child: Center(
            child: SizedBox(
              width: 20.w,
              height: 20.w,
              child: CircularProgressIndicator(
                strokeWidth: 2.0,
                color: Colors.white,
              ),
            ),
          ),
        );
      }

      return Row(
        children: [
          // 浏览用户头像
          if (viewedUsers.isNotEmpty) ...[
            SizedBox(
              height: 44.w,
              width: viewedUsers.length > 1 ? 30.w * viewedUsers.length : 44.w,
              child: Stack(
                children: List.generate(
                  viewedUsers.length > 4 ? 4 : viewedUsers.length,
                  (index) => Positioned(
                    left: index * 20.w,
                    child: Container(
                      height: 44.w,
                      width: 44.w,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(color: Colors.white, width: 2),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            blurRadius: 4,
                            spreadRadius: 1,
                          ),
                        ],
                      ),
                      child: ClipOval(
                        child:
                            viewedUsers[index].avatar != null
                                ? Image.asset(
                                  viewedUsers[index].avatar!,
                                  fit: BoxFit.cover,
                                )
                                : Container(
                                  color: Colors.grey[300],
                                  child: Icon(
                                    Icons.person,
                                    size: 25.sp,
                                    color: Colors.grey[600],
                                  ),
                                ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
            Text(
              'Already viewed',
              style: TextStyle(
                color: Colors.white70,
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
              ),
            ),
          ] else ...[
            // 没有浏览用户时显示
            Container(
              height: 44.w,
              width: 44.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Colors.white, width: 2),
              ),
              child: Center(
                child: Icon(Icons.add, size: 20.sp, color: Colors.white),
              ),
            ),
            SizedBox(width: 10.w),
            Text(
              'No one viewed',
              style: TextStyle(
                color: Colors.white70,
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
              ),
            ),
          ],
        ],
      );
    });
  }

  // 获取图片提供器（处理不同类型的图片路径）
  ImageProvider _getImageProvider(String? imageUrl) {
    if (imageUrl == null || imageUrl.isEmpty) {
      return AssetImage(Images.ceramic1);
    }

    // 处理本地文件路径（以/开头）
    if (imageUrl.startsWith('/')) {
      try {
        final file = File(imageUrl);
        if (file.existsSync()) {
          return FileImage(file);
        }
      } catch (e) {
        debugPrint('加载文件图片失败: $e');
      }
      return AssetImage(Images.ceramic1);
    }

    // 处理file:///开头的路径
    if (imageUrl.startsWith('file:///')) {
      String cleanPath = imageUrl.replaceFirst('file:///', '');
      return AssetImage(cleanPath);
    }

    // 处理http开头的网络图片
    if (imageUrl.startsWith('http')) {
      return NetworkImage(imageUrl);
    }

    // 默认作为asset加载
    return AssetImage(imageUrl);
  }

  // 构建加载指示器
  Widget _buildLoading() {
    return Center(
      child: CircularProgressIndicator(
        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
      ),
    );
  }

  // 主视图
  Widget _buildView() {
    return Obx(() {
      if (controller.isLoading.value) {
        return _buildLoading();
      }

      // 用户未登录且从导航栏进入时，只显示登录提示
      if (controller.pageUser.value == null && controller.isFromNavBar.value) {
        return _buildProfileHeader();
      }

      // 正常显示个人页面
      return Column(
        children: [_buildProfileHeader(), Expanded(child: _buildTabContent())],
      );
    });
  }

  // 构建AppBar
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: Colors.transparent,
      elevation: 0,
      centerTitle: true,
      title: Text(
        'personal',
        style: TextStyle(
          fontSize: 20.sp,
          color: Colors.white,
          fontWeight: FontWeight.w500,
        ),
      ),
      // 如果不是从导航栏进入，显示返回按钮
      leading:
          !controller.isFromNavBar.value
              ? IconButton(
                icon: Icon(Icons.arrow_back_ios, color: Colors.white),
                onPressed: () => Get.back(),
              )
              : null,
      // 右侧按钮
      actions: [
        Obx(() {
          // 如果用户未登录，不显示任何按钮
          if (controller.pageUser.value == null) {
            return SizedBox.shrink();
          }

          // 如果是个人主页，显示通知和设置按钮
          if (controller.isOwnProfile.value) {
            return Row(
              children: [
                IconButton(
                  icon: Icon(
                    IconFontIcons.iconNotify,
                    color: Colors.white,
                    size: 24.sp,
                  ),
                  onPressed: () => controller.goToNotifications(),
                ),
                IconButton(
                  icon: Icon(
                    IconFontIcons.iconSetup,
                    color: Colors.white,
                    size: 24.sp,
                  ),
                  onPressed: () => controller.goToSettings(),
                  padding: EdgeInsets.only(right: 10.w),
                ),
              ],
            );
          }
          // 如果是他人主页，显示举报按钮
          else {
            return IconButton(
              icon: Icon(IconFontIcons.iconReport, color: Colors.white),
              onPressed: () => controller.reportUser(),
              padding: EdgeInsets.only(right: 10.w),
            );
          }
        }),
      ],
    );
  }
}
